<template>
  <div class="excel-merge">
    <el-scrollbar :native="false" class="ctx">
      <div v-show="fileList.length < 1" class="no-data"
           :class="{'dragoverClass': isDragOver}" ref='dragRef' ondragstart="return false">
        <i class="el-icon-picture"></i>
        <span v-if="!isDragOver">请添加Excel文件，或将Excel文件拖至此处</span>
        <span v-else>松开即可添加</span>
      </div>
      <div v-for="(item, n) in fileList" :key="item.path + '-' + n" class="file-line" :class="{'dragging': dragging === item}"
           draggable="true"
           @dragstart="handleDragStart($event, item)"
           @dragover.prevent="handleDragOver($event, item)"
           @dragenter="handleDragEnter($event, item)"
           @dragend="handleDragEnd($event, item)"
      >
        <div>
          <div :title="item.path">{{ item.name }}</div>
          <div>{{ $utils.formatSize(item.size) }}</div>
        </div>
        <div>
          <el-button size="mini" icon="el-icon-close" circle @click="delFile(n)" title="删除"></el-button>
        </div>
      </div>
    </el-scrollbar>
    <div class="bottom-box">
      <!-- <div class="btn-line">
        <span class="btn-line-span" title="不影响结果">预览缩放</span>
        <div class="btn-line-div">
          <el-slider v-model="imgScale" :show-tooltip="false"></el-slider>
        </div>
      </div> -->
      
      <div class="btn-line" style="justify-content: flex-end">
        <span style="margin: 0 8px">共{{fileList.length}}个，合计{{totalSize}}</span>
        <el-button size="mini" icon="el-icon-minus" @click="delAll" :disabled="fileList.length < 1">清空全部</el-button>
        <el-button type="primary" size="mini" icon="el-icon-plus" @click="addFile">添加文件</el-button>
        <el-button type="success" size="mini" icon="el-icon-download"
                   @click="toDo"
                   :disabled="fileList.length < 1"
                   :loading="buttonLoading">
          开始
        </el-button>
      </div>

      <div class="btn-line">
        <el-progress style="width: 100%;"
                     class="my-progress"
                     :text-inside="true"
                     :stroke-width="20"
                     :percentage="progressPercentage"
                     :color="progressColors">
        </el-progress>
      </div>
    </div>
  </div>
</template>

<script>
import fs from 'fs'
import _path from 'path'

export default {
  name: 'ExcelMerge',
  data () {
    return {
      fileList: [], // 文件列表
      dragging: null, // 抓起的元素

      // tableTitleLines: 1, // 表头行数
      buttonLoading: false,

      userConfig: this.$store.getters['Config/getUserConfig'],
      progressPercentage: 0,
      progressColors: [
        {color: 'rgb(221, 221, 221)', percentage: 0},
        {color: 'rgb(65, 155, 255)', percentage: 99},
        {color: 'rgb(100, 200, 60)', percentage: 100}
      ],
      isDragOver: false
    }
  },
  computed: {
    totalSize () {
      return this.$utils.formatSize(this.fileList.reduce((pre, cur) => {
        return pre + cur.size
      }, 0))
    }
  },
  created () {
    console.log(`${this.$options.name} created`)
  },
  mounted () {
    console.log(`${this.$options.name} mounted`)
    this.$refs.dragRef.ondragenter = (e) => {
      e.preventDefault() // 阻止拖入时的浏览器默认行为
      this.isDragOver = true
    }
    this.$refs.dragRef.ondragover = (e) => {
      e.preventDefault() // 阻止拖来拖去的浏览器默认行为
    }
    this.$refs.dragRef.ondragleave = (e) => {
      e.preventDefault() // 阻止离开时的浏览器默认行为
      this.isDragOver = false
    }
    this.$refs.dragRef.ondrop = (e) => {
      e.preventDefault() // 阻止拖放后的浏览器默认行为
      this.isDragOver = false
      const files = e.dataTransfer.files
      if (files.length < 1) {
        console.log('未发现文件')
        return
      }
      console.log(files)
      for (let i = 0; i < files.length; i++) {
        let file = files[i]
        let extname = _path.extname(file.path)
        if (extname === '.xls' || extname === '.xlsx') {
          let fileStat = fs.statSync(file.path)
          this.fileList.push({
            name: _path.basename(file.path),
            size: fileStat.size,
            path: file.path
          })
        }
      }
    }
  },
  methods: {
    addFile () {
      this.$electron.remote.dialog.showOpenDialog({
        filters: [
          {name: 'Excel', extensions: ['xls', 'xlsx']}
        ],
        properties: [
          'openFile',
          'multiSelections'
        ]
      }).then(result => {
        result.filePaths.forEach(it => {
          let fileStat = fs.statSync(it)
          this.fileList.push({
            name: _path.basename(it),
            size: fileStat.size,
            path: it
          })
        })
      }).catch(err => console.log(err))
    },
    delFile (n) {
      this.fileList.splice(n, 1)
    },
    delAll () {
      this.fileList = []
    },
    toDo () {
      if (this.fileList.length < 1) {
        this.$message({
          showClose: true,
          message: '请添加文件',
          type: 'warning' // success/warning/info/error
        })
        return
      }
      this.buttonLoading = true
      this.progressPercentage = 0
      const filename = `合并-${this.$moment().format('YYYY-MM-DD-HH-mm-ss')}.csv`
      let data = {
        filename: filename,
        fileList: this.fileList,
        tableTitleLines: this.tableTitleLines,
        userConfig: this.userConfig
      }
      this.$process.create('excel-merge.js', data, res => {
        console.log('now persents', res)
        this.progressPercentage = Number.parseFloat((res.data * 100).toFixed(0))
      }).then(filePath => {
        let autoOpenFolder = this.userConfig['ExcelMerge.AutoOpenFolder']
        if (autoOpenFolder) this.$electron.shell.showItemInFolder(filePath)
      }).finally(() => {
        this.buttonLoading = false
      })
    },
    handleDragStart (e, item) {
      this.dragging = item
    },
    handleDragEnd (e, item) {
      this.dragging = null
    },
    // 首先把div变成可以放置的元素，即重写dragenter/dragover
    handleDragOver (e) {
      e.dataTransfer.dropEffect = 'move' // 在dragenter中针对放置目标来设置!
    },
    handleDragEnter (e, item) {
      e.dataTransfer.effectAllowed = 'move' // 为需要移动的元素设置dragstart事件
      if (item === this.dragging) {
        return
      }
      const newItems = [...this.fileList]
      const src = newItems.indexOf(this.dragging)
      const dst = newItems.indexOf(item)
      newItems.splice(dst, 0, ...newItems.splice(src, 1))
      this.fileList = newItems
    }
  }
}
</script>

<!--<style lang="scss" scoped>-->

<!--&gt;>>.el-progress-bar__outer {-->
<!--  border-radius:0;-->
<!--}-->
<!--&gt;>>.el-progress-bar__inner {-->
<!--  border-radius:0;-->
<!--}-->
<!--</style>-->

<style lang="less">
.my-progress {
  .el-progress-bar {
    .el-progress-bar__outer {
      border-radius: 2px;
      .el-progress-bar__inner {
        border-radius: 2px;
      }
    }
  }
}
</style>

<style lang="less" scoped>
.excel-merge {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;

  .ctx {
    width: 100%;
    flex: 1;

    .no-data {
      width: 100%;
      height: 300px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: @wxColorGray;

      i {
        font-size: 128px;
      }

      &.dragoverClass {
        color: limegreen;
        * {
          pointer-events: none;
        }
      }
    }

    .file-line {
      padding: 0 10px;
      margin: 20px 0;
      display: flex;
      align-items: center;
      justify-content: space-between;

      &:not(.btn):hover {
        background: @themeColor20;
      }

      &.dragging {
        background: @themeColor40;
      }
    }
  }

  .bottom-box {
    width: 100%;
    height: auto;
    background-color: white;

    .btn-line {
      width: calc(100% - 32px);
      padding: 0 16px;
      margin: 8px 0;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      overflow: hidden;
      transition: all .3s;
      max-height: 60px;

      &.hidden {
        max-height: 0;
        margin: 0;
      }

      .btn-line-span {
        padding: 0 8px 0 0;
        width: 70px;
        text-align: right;
      }

      .btn-line-div {
        padding: 0;
        flex: 1;
      }
    }
  }
}
</style>
